package com.elcom.player;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class playserver extends Activity{
	private static String HISTORY_FILE="history.json";
	//private EditText m_url;
	private Button 	m_go;
	private AutoCompleteTextView address;
	private URLHistory history=null;
	private CustomAdapter mAdapterListFilm;
	private ArrayList<String> mListFilm;
	private Dialog dialog ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme);
		setContentView(R.layout.playserver);
		
		//address.addTextChangedListener(addressChangeWatcher);
		
		//m_url = (EditText)findViewById(R.id.playserver_url);
		//m_url.setSelection(m_url.getText().length());
		address=(AutoCompleteTextView)findViewById(R.id.server_address);
		address.addTextChangedListener(addressChangeWatcher);

		m_go = (Button)findViewById(R.id.server_go);
		m_go.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goPlayServer();
			}
		});
		
		history=new URLHistory(this,android.R.layout.simple_dropdown_item_1line);
		try {
			File historyFile=new File(getFilesDir(), HISTORY_FILE);
			if (historyFile.exists()) {
				BufferedReader in=new BufferedReader(new InputStreamReader(openFileInput(HISTORY_FILE)));
				String str;
				StringBuilder buf=new StringBuilder();
				while ((str = in.readLine()) != null) {
					buf.append(str);
					buf.append("\n");
				}
				in.close();
				history.load(buf.toString());
			}
		} catch (Throwable t) {
			Log.e("EVPlayer", "Exception in loading history", t);
			//goBlooey(t);
        }
		address.setAdapter(history);
		address.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				address.setText("");
				return false;
			}
		});
	}
	private void goPlayServer(){

		// TODO Auto-generated method stub
		final String url = address.getText().toString();
		history.update(address.getText().toString());
		if(url.substring( url.length()-4,url.length()).equals(".mp4") || 
		   url.substring( url.length()-4,url.length()).equals(".MP4")){
			Intent intent =  new Intent(playserver.this, VideoPlayerActivity.class);
			intent.putExtra("videofilename", address.getText().toString());
			startActivity(intent);
		}else{

			AlertDialog.Builder builder = new AlertDialog.Builder(playserver.this);
			builder.setTitle("Select film");
			ListView modeList = new ListView(playserver.this);
			mListFilm = new ArrayList<String>();
			new ParserTask().execute(url);
			mAdapterListFilm =  new CustomAdapter(playserver.this, mListFilm);
			modeList.setAdapter(mAdapterListFilm);
			builder.setView(modeList);
		    dialog = builder.create();
			dialog.show();
			//Select Subttile
			modeList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					String ss =  url+mListFilm.get(arg2);
					history.update(ss);
					Intent intent =  new Intent(playserver.this, VideoPlayerActivity.class);
					intent.putExtra("videofilename", ss);
					startActivity(intent);
				}
			});
		}
	
	}
	private class ParserTask extends AsyncTask<String, Void, Integer>{
		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				String ss;
				Document doc = Jsoup.connect(params[0]).get();
				Elements eles = doc.select("tbody > tr:has(td)");
				Iterator<Element> ite = eles.iterator();
				while(ite.hasNext()){
					Element ele = ite.next();
					ss =  ele.select("a").first().attr("href");
					if(ss.contains(".mp4") || ss.contains(".MP4")){
						mListFilm.add(ss);
					}
				}
				Log.d("nna",String.valueOf(mListFilm.size()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mAdapterListFilm.notifyDataSetChanged();
		}
		
		
		
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		try {
			OutputStream out=openFileOutput(HISTORY_FILE,MODE_PRIVATE);
			OutputStreamWriter writer=new OutputStreamWriter(out);
			history.save(writer);
			writer.close();
		}
		catch (Throwable t) {
			Log.e("EVPlayer", "Exception writing history", t);
			//goBlooey(t);
		}
	}
	private TextWatcher addressChangeWatcher=new TextWatcher() {
		public void afterTextChanged(Editable s) {
			m_go.setEnabled(s.length()>0);
		}
		
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// no-op
		}
		
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// no-op
		}
	};
}
